﻿#include "const.h"
#include "ConfigManager.h"
#include "RedisManager.h"
#include "CServer.h"
#include "AsioIOServicePool.h"
#include "ChatGrpcServiceImpl.h"

#include <csignal>
#include <boost/asio.hpp>
#include <iostream>

int main()
{
	auto& cfg = ConfigManager::getInstance();
	auto server_name = cfg["SelfServer"]["Name"];
	try {
		std::cout << "this is ChatServer1......" << server_name << std::endl;
		auto pool = AsioIOServicePool::getInstance();
		// 将登录数设置为0 
		RedisManager::getInstance()->hSet(LOGIN_COUNT, server_name, "0");

		// 定义一个GrpcServer
		std::string server_address(cfg["SelfServer"]["Host"] + ":" + cfg["SelfServer"]["RPCPort"]);
		ChatGrpcServiceImpl service;
		grpc::ServerBuilder builder;
		// 监听端口，添加服务
		builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
		builder.RegisterService(&service);

		// 创建并启动grpc服务器
		std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
		std::cout << "RPC Server listening on " << server_address << std::endl;

		// 单独启动一个线程处理grpc服务
		std::thread  grpc_server_thread([&server]() {
			server->Wait();
		});

		boost::asio::io_context ioc;
		boost::asio::signal_set signals(ioc, SIGINT, SIGTERM);
		signals.async_wait([&ioc, pool, &server](auto, auto) {
			// io_context一旦停止，那么所有处理的异步事件马上返回
			ioc.stop();
			pool->stop();
			server->Shutdown();
		});

		auto port_str = cfg["SelfServer"]["Port"];
		CServer s( ioc, atoi(port_str.c_str()) );
		// 在CServer里绑定了监听对方连接的事件，ioc不会立刻退出
		ioc.run();
		RedisManager::getInstance()->hDel(LOGIN_COUNT, server_name);
		RedisManager::getInstance()->close();
		grpc_server_thread.join();
	}
	catch (std::exception& e) {
		std::cerr << "Exception: " << e.what() << std::endl;
		RedisManager::getInstance()->hDel(LOGIN_COUNT, server_name);
		RedisManager::getInstance()->close();
	}
}

